package com.my.socket.nio.v5;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class Client {
    private static final Logger LOGGER = LoggerFactory.getLogger(Client.class);

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            SocketChannel socketChannel = SocketChannel.open();
            InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1",9999);
            socketChannel.connect(inetSocketAddress);

            ByteBuffer byteBuffer = ByteBuffer.wrap("I am Alex Zhong".getBytes());
            socketChannel.write(byteBuffer);

            byteBuffer = ByteBuffer.allocate(1024);
            socketChannel.read(byteBuffer);
            socketChannel.close();
            LOGGER.info("receive: {}", new String(byteBuffer.array()));

//            Socket socket = new Socket();
//            socket.connect(new InetSocketAddress("127.0.0.1",9999));
//            OutputStream outputStream = socket.getOutputStream();
//            outputStream.write("I am Alex Zhong".getBytes());
//
//            InputStream inputStream = socket.getInputStream();
//            byte[] bytes = new byte[1024];
//            inputStream.read(bytes);
//            LOGGER.info("receive: {}", new String(bytes));
//            socket.close();
        }

        LOGGER.error("it takes {} second(s)...", (System.currentTimeMillis() - start) / 1000.00);
    }
}
